package com.haiyi.software.app.basic;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.Header;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.haiyi.software.app.HiChat;
import com.haiyi.software.app.MainApplication;
import com.haiyi.software.entity.UserInfo;
import com.haiyi.software.tools.MyTools;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.ResponseHandlerInterface;

public abstract class HiChatImageBasic extends HiChatVoiceBasic {

	private final static String TAG = "HiChatImageBasic";

	protected abstract void UploadImageSuccess();

	protected String imageFileSrc;

	protected JsonObject jsonReturnImage = null;

	protected void choseLocalImage() {

		Uri imageFileUri;

		String imageFileName;

		imageFileName = MainApplication.getInstance().getMineUserInfo()
				.getUid()
				+ "_" + System.currentTimeMillis() + ".jpg";

		String imgSrc = "file://"
				+ MainApplication.getInstance().getAppImageDirectory() + "/"
				+ imageFileName;

		imageFileSrc = MainApplication.getInstance().getAppImageDirectory()
				+ "/" + imageFileName;

		imageFileUri = Uri.parse(imgSrc);

		Intent intent = null;
		intent = new Intent(Intent.ACTION_GET_CONTENT, null);
		intent.setType("image/*");
		intent.putExtra("crop", "true");
		// intent.putExtra("aspectX", 1);
		// intent.putExtra("aspectY", 1);
		// intent.putExtra("outputX", 800);
		// intent.putExtra("outputY", 800);
		intent.putExtra("scale", true);
		intent.putExtra("return-data", false);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, imageFileUri);
		intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
		intent.putExtra("noFaceDetection", false);

		startActivityForResult(intent, HiChat.SHOW_SUB_LOCAL_IMAGE);

	}

	@Deprecated
	protected void createImageThumb(String imageThumbFile) {

		// BitmapFactory.Options options = new BitmapFactory.Options();
		//
		// options.inJustDecodeBounds = true;
		//
		// BitmapFactory.decodeFile(imageFile, options);
		//
		// int be = (int) (options.outWidth / (float) 200);
		// if (be <= 0) {
		// be = 1;
		// }
		// options.inSampleSize = be;
		//
		// options.inJustDecodeBounds = false;
		//
		// Bitmap bmp = BitmapFactory.decodeFile(imageFile, options);
		//
		// File fileImgThumb = new File(imageThumbFile);
		//
		// try {
		//
		// FileOutputStream out = new FileOutputStream(fileImgThumb);
		//
		// bmp.compress(Bitmap.CompressFormat.JPEG, 90, out);
		// out.flush();
		// out.close();
		//
		// } catch (Exception e) {
		// // TODO 自动生成的 catch 块
		// e.printStackTrace();
		// }
	}

	protected void uploadImage(String imageSrc) {

		File imageFile = new File(imageSrc);

		if (imageFile.exists() && imageFile.length() > 0) {

			AsyncHttpClient client = new AsyncHttpClient();
			String contType = URLConnection.guessContentTypeFromName(imageSrc);
			Log.i("contType", contType);
			RequestParams params = new RequestParams();
			params.put("args", getJsonArgs(imageFile));
			try {
				params.put("attfile", imageFile, contType);

				client.setTimeout(160);

				client.post(str_server + str_requestNameUpload, params,
						rpHandler);

			} catch (FileNotFoundException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
		}

	}

	private ResponseHandlerInterface rpHandler = new AsyncHttpResponseHandler() {

		@Override
		public void onProgress(int bytesWritten, int totalSize) {
			// TODO 自动生成的方法存根
			super.onProgress(bytesWritten, totalSize);
		}

		@Override
		public void onSuccess(int statusCode, Header[] headers,
				byte[] responseBody) {

			try {

				String str_jsonReturn = new String(responseBody, "UTF-8");

				Log.i(TAG, str_jsonReturn);

				JsonParser parse = new JsonParser();

				jsonReturnImage = parse.parse(str_jsonReturn).getAsJsonObject();

				UploadImageSuccess();

			} catch (UnsupportedEncodingException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
		}

		@Override
		public void onFailure(int statusCode, Header[] headers,
				byte[] responseBody, Throwable error) {
			// TODO 自动生成的方法存根

		}
	};

	private String getJsonArgs(File imageFile) {

		UserInfo myInfo = MainApplication.getInstance().getMineUserInfo();

		if (myInfo != null) {

			Map<String, Object> validator = new HashMap<String, Object>();

			validator.put("uid", myInfo.getUid());
			validator.put("uname", myInfo.getUname());
			validator.put("pwd", myInfo.getPwd());
			validator.put("uguid", myInfo.getUguid());

			Map<String, Object> body = new HashMap<String, Object>();

			body.put("typeid", 3);

			body.put("filedatasrc", imageFile.getPath());

			body.put("videolong", 0);

			body.put("md5id", MyTools.getMd5ByFile(imageFile));

			Map<String, Object> args = new HashMap<String, Object>();
			args.put("validator", validator);
			args.put("body", body);

			Gson gson = new Gson();
			String s = gson.toJson(args);

			Log.i("argsJson", s);
			return s;
		} else {
			return "";
		}

	}
}
